package com.pigdroid.adbsqlite.manager;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;


public class PortWorker implements Runnable {

	private static final int BUFF_SIZE = 1024 * 4;
	private ConsoleLineListener listener;
	private String name;
	private SocketChannel socketChannel;
	private StringBuffer currentLine;
	private ByteBuffer buffer;

	public PortWorker(int localport, String name, ConsoleLineListener listener) {
		try {
			socketChannel = SocketChannel.open(new InetSocketAddress("localhost", localport));
			this.listener = listener;
			this.name = name;
			buffer = ByteBuffer.allocate(BUFF_SIZE);
			currentLine = new StringBuffer();
		} catch (UnknownHostException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
	
	public void run() {
		try {
			while (dispatchPendingLines()) {
				
			}
			readMoreBytes();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	private boolean dispatchPendingLines() {
		int pos = currentLine.indexOf("\n");
		if (pos > -1) {
			String msg = currentLine.subSequence(0,  pos).toString();
			currentLine.delete(0, pos + 1);
			listener.onLineReceived(name, msg);
		}
		return pos > -1;
	}

	private void readMoreBytes() throws IOException {
		int count = socketChannel.read(buffer);
		buffer.rewind();
		if (count > 0) {
			for (int i = 0; i < count; i++) {
				currentLine.append((char)buffer.get());
			}
		}
		buffer.clear();
	}

}
